const ids = location.search.slice(1).split('=')[1]
const $ = (el)=>document.querySelector(el)
const gets = (el) =>[...document.querySelectorAll(el)]
const list = []
const audio = $('.audio')
console.log(ids)
async function renderSong() {
    try{
        const res = await new axios('http://zyxcl.xyz/music/api/song/detail',{
            params:{
                ids
            }
        })
        // console.log(res)
        // 背景图片地址
        let data = res.data.songs
        // console.log(data)
        $('.al-img img').src = data[0].al.picUrl
        $('.bg-img').style.backgroundImage = `url(${data[0].al.picUrl})`
        $('.song-info-name').innerHTML = data[0].name
        $('.song-info-singer').innerHTML = data[0].ar.map(v=>v.name).join(' ')
    }
    catch(e){
        console.log(e)
    }
    finally{
        console.log('加载完成')
    }
}
renderSong()
// 歌词内容
let lrcArr = []
async function lyrFn() {
    try{
        const res = await new axios(`http://zyxcl.xyz/music/api/lyric`,{
            params:{
                id:ids
            }
        })
        console.log(res)
        lrcArr = res.data.lrc.lyric.split('\n').filter(Boolean).map(item => {
            const [time, text] = item.split(']')
            const [m, s] = time.slice(1).split(':')
            return {
              time: m * 60 + s * 1,
              text
            }
          })
        //   console.log(lrcArr)
          $('.lyric').innerHTML = lrcArr.map(item =>`<p class="lyric-item">${item.text}</p>`).join('')
    }
    catch(e){
        console.log(e)
    }
    finally{
        console.log('加载完成')
    }
}
lyrFn()

// 歌词滚动 
// 歌曲播放地址
async function getUrl() {
    try{
        const res = await new axios('https://zyxcl.xyz/music/api/song/url',{
            params:{
                id:ids
            }
        })
        console.log(res)
        audio.src = res.data.data[0].url
    }
    catch(e){
        console.log(e)
    }
    finally{
        console.log('加载完成')
    }
}
getUrl()

// 歌曲播放
$('.play-btn-wrap').addEventListener('click',e =>{
    if(audio.paused){
        audio.play()
    }else{
        audio.pause()
    }
})
// 监听播放事件
audio.addEventListener('timeupdate',e=>{
    const index = lrcArr.findIndex((v, i) => {
        if (i === lrcArr.length - 1) return true
        return audio.currentTime >= v.time && audio.currentTime < lrcArr[i + 1].time
      })
      $('.lyric-item.active')?.classList.remove('active')
      gets('.lyric-item')[index]?.classList.add('active')
      if (gets('.lyric-item')[index]) {
        $('.lyric').scrollTop = gets('.lyric-item')[index].offsetTop - 60
      }
})
